<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\LandingCompany;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
use Log;

class InvoiceController extends Controller
{
    /**
     * 获取发票列表
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;

            $query = Invoice::with(['tenant', 'landingCompany'])
                ->where('tenant_id', $tenantId);
            
            // 搜索条件
            if ($request->filled('invoice_id')) {
                $query->searchInvoiceId($request->input('invoice_id'));
            }
            
            if ($request->filled('billing_type')) {
                $query->billingType($request->input('billing_type'));
            }
            
            if ($request->filled('landing_company_id')) {
                $query->landingCompany($request->input('landing_company_id'));
            }
            
            if ($request->filled('billing_category')) {
                $query->where('billing_category', $request->input('billing_category'));
            }
            
            if ($request->filled('status')) {
                $query->status($request->input('status'));
            }
            
            // 时间范围查询
            if ($request->filled('start_date') && $request->filled('end_date')) {
                $query->applicationTimeRange($request->input('start_date'), $request->input('end_date'));
            }
            
            // 获取分页参数
            $page = (int) $request->input('page', 1);
            $perPage = (int) $request->input('per_page', 15);
            $perPage = max(1, min($perPage, 100));
            
            // 排序
            $sortBy = $request->input('sort_by', 'application_time');
            $sortOrder = $request->input('sort_order', 'desc');
            
            if (in_array($sortBy, ['application_time', 'invoice_amount', 'status', 'created_at'])) {
                $query->orderBy($sortBy, $sortOrder === 'asc' ? 'asc' : 'desc');
            } else {
                $query->orderBy('application_time', 'desc');
            }
            
            // 执行查询
            $result = $query->paginate($perPage, ['*'], 'page', $page);
            
            return response()->json([
                'code' => 0,
                'message' => '获取发票列表成功',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取发票列表失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取发票详情
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            $invoice = Invoice::with(['tenant', 'landingCompany'])
                ->where('tenant_id', $tenantId)
                ->where('id', $id)
                ->first();
            
            if (!$invoice) {
                return response()->json([
                    'success' => false,
                    'message' => '发票不存在',
                    'data' => null
                ], 404);
            }
            
            return response()->json([
                'code' => 0,
                'message' => '获取发票详情成功',
                'data' => $invoice
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取发票详情失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 创建发票申请
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $tenantId = $user->tenant_id;

            $tenant = Tenant::find($tenantId);

            if (! $tenant) {
                return response()->json([
                    'success' => false,
                    'message' => '租户信息不存在，请联系管理员配置',
                    'data' => null
                ], 404);
            }

            $validatedData = $request->validate([
                'landing_company_id' => 'required|exists:landing_companies,id',
                'invoice_amount' => 'required|numeric|min:0.01|max:9999999999999.99',
                'billing_type' => 'required|in:6_regular,6_special,differential_regular',
                'billing_category' => 'required|string|max:100',
                'invoice_content' => 'nullable|string',
                'related_tasks' => 'nullable',
                'invoice_remarks' => 'nullable|string|max:500',
            ]);

            if ($tenant->invoiceable_amount !== null && (float) $validatedData['invoice_amount'] > (float) $tenant->invoiceable_amount) {
                return response()->json([
                    'success' => false,
                    'message' => '开票金额不能超过可开票金额',
                    'data' => null,
                ], 422);
            }

            if (! $tenant->tax_registration_number || ! $tenant->company_name || ! $tenant->bank_name || ! $tenant->bank_account) {
                return response()->json([
                    'success' => false,
                    'message' => '租户开票资料不完整，请先在开票信息中补全',
                    'data' => null,
                ], 422);
            }

            $relatedTasks = $validatedData['related_tasks'] ?? null;
            if (is_array($relatedTasks)) {
                $relatedTasks = json_encode(array_values($relatedTasks), JSON_UNESCAPED_UNICODE);
            } elseif (is_string($relatedTasks)) {
                $relatedTasks = trim($relatedTasks) ?: null;
            }

            $invoice = Invoice::create([
                'tenant_id' => $tenant->id,
                'landing_company_id' => $validatedData['landing_company_id'],
                'invoice_amount' => round($validatedData['invoice_amount'], 2),
                'billing_type' => $validatedData['billing_type'],
                'billing_category' => $validatedData['billing_category'],
                'invoice_title' => $tenant->company_name ?? $tenant->name,
                'tax_number' => $tenant->tax_registration_number,
                'company_address' => $tenant->address,
                'company_phone' => $tenant->invoice_contact_phone ?? $tenant->contact_phone,
                'bank_name' => $tenant->bank_name,
                'bank_account' => $tenant->bank_account,
                'invoice_content' => $validatedData['invoice_content'] ?? '劳务服务费',
                'related_tasks' => $relatedTasks,
                'invoice_remarks' => $validatedData['invoice_remarks'] ?? null,
                'status' => Invoice::STATUS_NEW,
                'created_by' => $request->user()?->id,
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '发票申请创建成功',
                'data' => $invoice->load(['tenant', 'landingCompany'])
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '创建发票申请失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 更新发票申请
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $invoice = Invoice::where('tenant_id', $tenantId)
                ->where('id', $id)
                ->first();
            
            if (!$invoice) {
                return response()->json([
                    'success' => false,
                    'message' => '发票不存在',
                    'data' => null
                ], 404);
            }
            
            // 只有新建状态的发票可以编辑
            if ($invoice->status !== Invoice::STATUS_NEW) {
                return response()->json([
                    'success' => false,
                    'message' => '只有新建状态的发票可以编辑',
                    'data' => null
                ], 400);
            }
            
            $tenant = Tenant::find($tenantId);

            if (! $tenant) {
                return response()->json([
                    'success' => false,
                    'message' => '租户信息不存在，请联系管理员配置',
                    'data' => null
                ], 404);
            }

            $validatedData = $request->validate([
                'landing_company_id' => 'required|exists:landing_companies,id',
                'invoice_amount' => 'required|numeric|min:0.01|max:9999999999999.99',
                'billing_type' => 'required|in:6_regular,6_special,differential_regular',
                'billing_category' => 'required|string|max:100',
                'invoice_content' => 'nullable|string',
                'related_tasks' => 'nullable',
                'invoice_remarks' => 'nullable|string|max:500'
            ]);

            if ($tenant->invoiceable_amount !== null && (float) $validatedData['invoice_amount'] > (float) $tenant->invoiceable_amount) {
                return response()->json([
                    'success' => false,
                    'message' => '开票金额不能超过可开票金额',
                    'data' => null,
                ], 422);
            }

            $relatedTasks = $validatedData['related_tasks'] ?? null;
            if (is_array($relatedTasks)) {
                $relatedTasks = json_encode(array_values($relatedTasks), JSON_UNESCAPED_UNICODE);
            } elseif (is_string($relatedTasks)) {
                $relatedTasks = trim($relatedTasks) ?: null;
            }
            
            $invoice->update([
                'landing_company_id' => $validatedData['landing_company_id'],
                'invoice_amount' => round($validatedData['invoice_amount'], 2),
                'billing_type' => $validatedData['billing_type'],
                'billing_category' => $validatedData['billing_category'],
                'invoice_content' => $validatedData['invoice_content'] ?? $invoice->invoice_content,
                'related_tasks' => $relatedTasks,
                'invoice_remarks' => $validatedData['invoice_remarks'] ?? $invoice->invoice_remarks,
            ]);
            
            return response()->json([
                'code' => 0,
                'message' => '发票申请更新成功',
                'data' => $invoice->fresh()->load(['tenant', 'landingCompany'])
            ]);
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'data' => null,
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新发票申请失败：' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 删除发票申请
     */
    public function destroy(Request $request, $id): JsonResponse
    {
        try {
            $tenantId = $request->user()->tenant_id;
            
            $invoice = Invoice::where('tenant_id', $tenantId)
                ->where('id', $id)
                ->first();
            
            if (!$invoice) {
                return response()->json([
                    'success' => false,
                    'message' => '发票不存在',
                    'data' => null
                ], 404);
            }
            
            // 只有新建状态的发票可以删除
            if ($invoice->status !== Invoice::STATUS_NEW) {
                return response()->json([
                    'success' => false,
                    'message' => '只有新建状态的发票可以删除',
                    'data' => null
                ], 400);
            }
            
            $invoice->delete();
            
            return response()->json([
                'code' => 0,
                'message' => '发票申请删除成功',
                'data' => null
            ]);
            
        } catch (\Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => '删除发票申请失败：' . $e->getMessage(),
                    'data' => null
                ], 500);
        }
    }

    public function download(Request $request, Invoice $invoice)
    {
        $tenantId = $request->user()->tenant_id;
        Log::debug("download {$invoice->tenant_id}:{$tenantId}");
        if ($invoice->tenant_id != $tenantId) {
            abort(404, '发票不存在');
        }

        if (! $invoice->invoice_file_path) {
            abort(404, '发票文件不存在');
        }

        $disk = config('invoice.storage_disk', config('filesystems.default', 'local'));
        $storage = Storage::disk($disk);

        if (! $storage->exists($invoice->invoice_file_path)) {
            abort(404, '发票文件不存在');
        }

        $filename = basename($invoice->invoice_file_path) ?: ($invoice->invoice_number . '.pdf');

        return $storage->download($invoice->invoice_file_path, $filename);
    }

    /**
     * 获取开票类型选项
     */
    public function billingTypeOptions(Request $request): JsonResponse
    {
        try {
            $options = collect(Invoice::getBillingTypeOptions())
                ->map(function ($label, $value) {
                    return [
                        'value' => $value,
                        'label' => $label
                    ];
                })
                ->values()
                ->toArray();
            
            return response()->json([
                'code' => 0,
                'message' => '获取开票类型选项成功',
                'data' => $options
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取开票类型选项失败：' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }

    /**
     * 获取开票类目选项
     */
    public function billingCategoryOptions(Request $request): JsonResponse
    {
        try {
            $options = Invoice::getBillingCategoryOptions();
            
            return response()->json([
                'code' => 0,
                'message' => '获取开票类目选项成功',
                'data' => $options
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取开票类目选项失败：' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }

    /**
     * 获取开票状态选项
     */
    public function statusOptions(Request $request): JsonResponse
    {
        try {
            $options = collect(Invoice::getStatusOptions())
                ->map(function ($label, $value) {
                    return [
                        'value' => $value,
                        'label' => $label
                    ];
                })
                ->values()
                ->toArray();
            
            return response()->json([
                'code' => 0,
                'message' => '获取开票状态选项成功',
                'data' => $options
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取开票状态选项失败：' . $e->getMessage(),
                'data' => []
            ], 500);
        }
    }
}
